package net.csdn.business.common.domain.issue;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import net.csdn.business.common.constant.CommonConstants;
import net.csdn.business.common.domain.common.ActionEventDto;
import net.csdn.business.common.domain.issue.event.BaseEventDto;
import net.csdn.business.common.enums.ActionEventEnum;
import net.csdn.business.common.utils.IpUtil;
import net.csdn.business.common.utils.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import java.io.Serializable;
import java.util.Date;

/**
 * @author likun
 * @date 2022/11/16 16:37
 */
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class IssueEventDto extends ActionEventDto implements Serializable {
    private IssueActionEventEnum action;

    /**
     * 事件时间
     * change事件是时序类型，目前基于list的方式，多线程消费的情况，可能出现时序错轮的问题
     * 通过增加事件时间，一定程度解决乱序问题（时间精度、多机器时钟一致性等问题还会出现问题）
     */
    private Date createTime;

    private String ip;

    private String payload;

    private IssueEventDto(IssueActionEventEnum action, String traceId, String payload) {
        super(ActionEventEnum.ISSUE, traceId);
        this.action = action;
        this.payload = payload;
        this.createTime = new Date();
        this.ip = IpUtil.getIp();
    }

    private IssueEventDto() {
        super();
    }

    public static <T extends BaseEventDto> IssueEventDto build(IssueActionEventEnum action, T payload) {
        return new IssueEventDto(action, getTraceId(payload.getId()), JsonUtil.toJsonString(payload));
    }

    private static String getTraceId(String issueId) {
        String traceId = MDC.get(CommonConstants.TRACE_ID);
        return StringUtils.isBlank(traceId) ? issueId : traceId;
    }
}